const express = require("express");
const router = express.Router();
const multer = require("multer");
const path = require("path");
const ResponseHelper = require("../ResponseHelper");
const os = require("os");
const fileUrl = require("../../tools/fileUrl");

const allowedMimetype = [
  "image/jpeg",
  "image/jpg",
  "jpg",
  "jpeg",
  "image/png",
  "image/bmp",
  "gif",
  "video/x-matroska",
];

function fileFilter(req, file, cb) {
  // 这个函数应该调用 `cb` 用boolean值来指示是否应接受该文件
  if (allowedMimetype.includes(file.mimetype)) {
    //接受这个文件，使用`true`，像这样:
    cb(null, true);
  } else {
    // 拒绝这个文件，使用`false`，像这样:
    cb(new Error("Reject this type of picture"));
  }
  // 如果有问题，你可以总是这样发送一个错误:
  //cb(new Error('I don\'t have a clue!'))
}

const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    const type = JSON.parse(req.params.id).type;
    const id = JSON.parse(req.params.id).id;
    const id2 = JSON.parse(req.params.id).id2;
    const id3 = JSON.parse(req.params.id).id3;
    let uploadPath = `${fileUrl.uploadStaticPath}\\${id}\\${id2}`;
    const system = os.platform();
    if (system === "linux") {
      if (type == "local") {
        uploadPath = `${fileUrl.uploadStaticPath}/${id}/${id2}/${id3}`;
      } else {
        uploadPath = `${fileUrl.uploadStaticPath}/${id}/${id2}`;
      }
    }
    console.log("uploadPath", uploadPath);
    cb(null, uploadPath);
  },
  filename: function (req, file, cb) {
    console.log("===============req", req.params);
    const fileName = JSON.parse(req.params.id).name;
    console.log("===============fileName", fileName);
    let ext = path.extname(file.originalname);
    if (file.originalname === "blob" && file.mimetype != "image/bmp") {
      if (file.mimetype == "image/png") {
        ext = ".png";
      } else if (file.mimetype == "image/jpg") {
        ext = ".jpg";
      } else {
        ext = ".mp4";
      }
    } else if (file.originalname === "blob" && file.mimetype == "image/bmp") {
      ext = ".bmp";
    } else if (!ext && file.mimetype == "image/png") {
      ext = ".png";
    }
    cb(null, `${fileName}${ext}`);
  },
});

const upload = multer({
  storage: storage,
  limits: { fileSize: 1024 * 1024 * 10 },
  fileFilter,
});

router.post("/:id", upload.single("file"), (req, res, next) => {
  const type = JSON.parse(req.params.id).type;
  const id = JSON.parse(req.params.id).id;
  const id2 = JSON.parse(req.params.id).id2;
  const id3 = JSON.parse(req.params.id).id3;
  if (type && type == "local") {
    ResponseHelper.sendData(
      `http://${req.headers.host}/pubilc/uploads/${id}/${id2}/${id3}/${req.file.filename}`,
      res
    );
  } else {
    ResponseHelper.sendData(
      `http://${req.headers.host}/pubilc/uploads/${id}/${id2}/${req.file.filename}`,
      res
    );
  }
});

module.exports = router;
